package com.kehongborui.portal.service.impl;

import com.kehongborui.data.domain.Dept;
import com.kehongborui.data.repository.DeptRepository;
import com.kehongborui.portal.exception.SczcException;
import com.kehongborui.portal.model.DeptModel;
import com.kehongborui.portal.service.DeptService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.kehongborui.portal.enums.Error.DEPT_IS_EXISTS;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief 部门管理
 * @email 122162005@qq.com
 * @date 2018-09-26
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptRepository deptRepository;

    @Override
    public DeptModel save(DeptModel model) {
        Dept dept = new Dept();
        BeanUtils.copyProperties(model, dept);

        // 根据分类名称查询分类是否已经存在
        if (deptRepository.exists(Example.of(dept))) {
            throw new SczcException(String.format(DEPT_IS_EXISTS.getDesc(), model.getFullName()));
        }

        Dept save = deptRepository.save(dept);

        BeanUtils.copyProperties(save, model);
        return model;
    }

    @Override
    public void update(DeptModel model) {
        Dept dept = new Dept();
        BeanUtils.copyProperties(model, dept);

        Dept save = deptRepository.save(dept);
    }

    @Override
    public DeptModel findById(Integer id) {
        Dept dept = deptRepository.findOne(id);
        DeptModel model = new DeptModel();
        BeanUtils.copyProperties(dept, model);
        return model;
    }

    @Override
    public void deleteById(Integer id) {
        deptRepository.delete(id);
    }

    @Override
    public List<DeptModel> findAll() {
        List<Dept> deptList = deptRepository.findAll();
        // 将数据转换成model
        List<DeptModel> modelList = deptList.stream().map(classify -> {
            DeptModel model = new DeptModel();
            BeanUtils.copyProperties(classify, model);
            return model;
        }).collect(Collectors.toList());

        return modelList;
    }
}
